/*
 * 文件名：CreateFile.java
 * 版权：Copyright by Power7000 Team
 * 描述：
 * 修改人：严浪
 * 修改时间：2017年1月17日
 * 跟踪单号：
 * 修改单号：
 * 修改内容：
 */

package com.core;

import java.io.File;  
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;  
import java.io.FileWriter;
import java.io.IOException;  
import java.io.OutputStreamWriter;  
import java.io.Writer;  
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;  
import java.util.Date;
import java.util.HashMap;  
import java.util.List;  
import java.util.Map;  
  



import java.util.Map.Entry;
import java.util.Optional;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import com.github.javaparser.JavaParser;
import com.github.javaparser.ast.CompilationUnit;
import com.github.javaparser.ast.Modifier;
import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration;
import com.github.javaparser.ast.body.MethodDeclaration;
import com.github.javaparser.ast.stmt.BlockStmt;
import com.util.DateUtils;
import com.util.DeployPropertiesUtil;
import com.util.StringUtil;

import freemarker.template.Configuration;  
import freemarker.template.DefaultObjectWrapper;  
import freemarker.template.Template;  
import freemarker.template.TemplateException;  
  
public class CreateFile {  
    static String sql = null;  
    static DBHelper db1 = null;  
    static DBHelper db2 = null;  
    static ResultSet ret = null;  
    static ResultSet ret1 = null; 
    static  DeployPropertiesUtil utils;
    private static List<String> notFields=new ArrayList<>();
    public static void main(String[] args) {  
         notFields.add("create_by".toUpperCase());
         notFields.add("create_name".toUpperCase());
         notFields.add("update_by".toUpperCase());
         notFields.add("update_date".toUpperCase());
         notFields.add("create_date".toUpperCase());
         notFields.add("update_name".toUpperCase());
         utils = new DeployPropertiesUtil();
            String tableNames=utils.readPropertyByNameFromProperties("dataSource.table.name");
            tableNames=tableNames.trim();
            try {  
            List<Map<String,Object>> tableList=new ArrayList<Map<String,Object>>();
            if(StringUtils.isEmpty(tableNames)){
            	return ;
            }
            if(!tableNames.contains("*")&&!tableNames.contains("%")){
                tableNames="'"+tableNames.replace(",", "','")+"'";
               sql="show table status where name in("+tableNames+") ";
            }else if(tableNames.equals("*")){
                sql=" show table status  ";
            }else{
            	sql=" show table status  where name LIKE '"+tableNames+"'  ";
            }
                db1 = new DBHelper();//创建DBHelper对象  
                db2 = new DBHelper();//创建DBHelper对象  
                ret = db1.pst.executeQuery(sql);//执行语句，得到结果集  
                while (ret.next()) { 
                    String name = ret.getString(1); 
                    name=name.trim();
                    String comment = ret.getString(18); 
                    if(StringUtils.isEmpty(comment)){
                        comment=getMysqlNameToJavaName(name,false);
                    }
                    comment=comment.trim();
                    sql = "show full columns from "+name;//SQL语句  
                    ret1 = db2.pst.executeQuery(sql);//执行语句，得到结果集  
                    Map<String,Object> m=new HashMap<String,Object>();
                    //是否生成流程
                    Boolean isGenerate=Boolean.parseBoolean(utils.readPropertyByNameFromProperties("dataSource.bpmn.isGenerate"));
                    m.put("bpmnIsGenerate", isGenerate);
                    
                    m.put("sPname", name.toLowerCase());
                    m.put("sName", name.toUpperCase());
                    m.put("jName", getMysqlNameToJavaName(name,true));
                    m.put("jPname", getMysqlNameToJavaName(name,false));
                    m.put("jComment", comment);
                    m.put("createDate", DateUtils.formatDate(new Date(),"yyyy-MM-dd hh:mm:ss"));
                    String isCuBy="0";
                    m.put("createBy", utils.readPropertyByNameFromProperties("dataSource.create.user").trim());
                    m.put("packageName", utils.readPropertyByNameFromProperties("dataSource.package.name").trim());
                    List<Map<String,Object>> paramList=new ArrayList<Map<String,Object>>();
                    List<Map<String,Object>> baseParamList=new ArrayList<Map<String,Object>>();
                    while (ret1.next()) { 
                        Map<String,Object> pm=new HashMap<String,Object>();
                        String sName = ret1.getString(1);  
                        String sType = ret1.getString(2);  
                        String sKey=ret1.getString(5);
                        String sComment = ret1.getString(9);  
                        pm.put("sName", sName.trim().toUpperCase());
                        pm.put("sPname", sName.trim().toLowerCase());
                        pm.put("jName", getMysqlNameToJavaName(sName,false));
                        pm.put("jFname", getMysqlNameToJavaName(sName,true));
                        pm.put("jType", getMysqlTypeToJavaType(sType));
                        sType=sType.toUpperCase();
                        pm.put("sType", getMysqlTypeToMybatisType(sType));
                        if(StringUtils.isEmpty(sComment)){
                            pm.put("jComment", getMysqlNameToJavaName(sName,false));
                        }else{
                            pm.put("jComment", sComment.trim());
                        }
                        if(StringUtils.isNotEmpty(sKey)&&sKey.trim().equals("PRI")&&sName.trim().toUpperCase().equals("ID")){
                            m.put("jKey", pm);
                        }else if(!notFields.contains(pm.get("sName"))){
                            paramList.add(pm);
                        }else if(notFields.contains(pm.get("sName"))){
                        	baseParamList.add(pm);
                        	isCuBy="1";
                        }
                    }
                    m.put("isCuBy", isCuBy);
                    m.put("paramList", paramList);
                    m.put("baseParamList", baseParamList);
                    tableList.add(m);
                }
            if(ret!=null){
                ret.close();  
            }
            if(ret1!=null){  
                ret1.close();
            }
            if(db2!=null){  
                db2.close();
            }
            db1.close();//关闭连接  
            
            Boolean isAdd=Boolean.parseBoolean(utils.readPropertyByNameFromProperties("dataSource.addfun.isAdd"));
            if(isAdd){
            	addFunction(tableList);
            }else{
            	createFileList(tableList);
            }
            System.out.println("创建完成");
            } catch (SQLException e) {  
                    e.printStackTrace();  
           }  
          
    }
    //添加方法
    public static void addFunction(List<Map<String,Object>> tableList){
    	String funName=utils.readPropertyByNameFromProperties("dataSource.addfun.name");
    	String funComment=utils.readPropertyByNameFromProperties("dataSource.addfun.comment");
    	String retType=utils.readPropertyByNameFromProperties("dataSource.addfun.return.type");
    	String parameters=utils.readPropertyByNameFromProperties("dataSource.addfun.parameters");
    	Map<String,String> params=new HashMap<String, String>();
    	if(StringUtil.isNotEmpty(parameters)){
    		String[] split = parameters.split(",");
    		for (int i = 0; i < split.length; i++) {
    			String[] kv = split[i].split(":");
    			params.put(kv[0], kv[1]);
			}
    	}
    	String sql=utils.readPropertyByNameFromProperties("dataSource.addfun.sql");
    	Boolean isGenerate=false;
        for(Map<String,Object> table:tableList){
        	
        	isGenerate=Boolean.parseBoolean(utils.readPropertyByNameFromProperties("dataSource.dao.isGenerate"));
        	if(isGenerate){
        		String path=utils.readPropertyByNameFromProperties("dataSource.provider.path")+"\\src\\main\\java\\com\\ydcloud\\"+table.get("packageName")+"\\dao\\"+table.get("jName")+"Dao.java";
        		File file=new File(path);
        		if(file.exists()){
					try {
						CompilationUnit cu = JavaParser.parse(new FileInputStream(path));
						Optional<ClassOrInterfaceDeclaration> classByName = cu.getInterfaceByName(table.get("jName")+"Dao");
						ClassOrInterfaceDeclaration orElse = classByName.orElse(null);
						//接口方法添加
						MethodDeclaration addMethod = orElse.addMethod(funName);
						addMethod.setType(retType); //添加返回类型
						//添加入参
						Set<Entry<String, String>> entrySet = params.entrySet();
						for (Entry<String, String> entry : entrySet) {
							addMethod.addParameter(entry.getValue(), entry.getKey());//添加入参
						}
				        addMethod.setBlockComment(funComment); //添加备注
				        addMethod.removeBody();
				        writeJava(cu, path);
					} catch (FileNotFoundException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

        		}
        	}
        	isGenerate=Boolean.parseBoolean(utils.readPropertyByNameFromProperties("dataSource.serviceImpl.isGenerate"));
        	if(isGenerate){
        		String path=utils.readPropertyByNameFromProperties("dataSource.provider.path")+"\\src\\main\\java\\com\\ydcloud\\"+table.get("packageName")+"\\service\\impl\\"+table.get("jName")+"ServiceImpl.java";
        		File file=new File(path);
        		if(file.exists()){
					try {
						CompilationUnit cu = JavaParser.parse(new FileInputStream(path));
						Optional<ClassOrInterfaceDeclaration> classByName = cu.getClassByName(""+table.get("jName")+"ServiceImpl");
						ClassOrInterfaceDeclaration orElse = classByName.orElse(null);
						//接口方法添加
						MethodDeclaration addMethod = orElse.addMethod(funName,Modifier.PUBLIC);
						addMethod.setType(retType); //添加返回类型
						addMethod.addMarkerAnnotation("Override");
						//添加入参
						Set<Entry<String, String>> entrySet = params.entrySet();
						String paramStr="";
						for (Entry<String, String> entry : entrySet) {
							addMethod.addParameter(entry.getValue(), entry.getKey());//添加入参
							if(StringUtil.isNotEmpty(paramStr)){
								paramStr+=","+entry.getKey();
							}else{
								paramStr=entry.getKey();
							}
						}
				        addMethod.setBlockComment(funComment); //添加备注
				        BlockStmt body=new BlockStmt();
						body.addStatement("return "+table.get("jPname")+"Dao."+funName+"("+paramStr+");");  //添加java语句
						addMethod.setBody(body);
				        writeJava(cu, path);
					} catch (FileNotFoundException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

        		}
        	}
        	isGenerate=Boolean.parseBoolean(utils.readPropertyByNameFromProperties("dataSource.mapper.isGenerate"));
        	if(isGenerate){
        		String path=utils.readPropertyByNameFromProperties("dataSource.provider.path")+"\\src\\main\\resources\\mybatis\\"+table.get("jName")+"Mapper.xml";
        		File file=new File(path);
        		if(file.exists()){
        			Document document = getDocument(file);
        			//获取XML文档的根标签
        	        Element rootElement = document.getRootElement();
        	        //增加标签
        	        Element select = rootElement.addElement("select");
        	        //增加属性值 
        	        select.addAttribute("id", funName);
        	        Set<Entry<String, String>> entrySet = params.entrySet();
					for (Entry<String, String> entry : entrySet) {
						select.addAttribute("parameterType", entry.getValue());
						break;
					}
					select.addAttribute("resultType", retType);
					select.addComment(funComment);
					select.setText(sql);
        	        try {
        				writeXml(document, path);
        			} catch (IOException e) {
        				// TODO Auto-generated catch block
        				e.printStackTrace();
        			}
        		}
        	}
        	isGenerate=Boolean.parseBoolean(utils.readPropertyByNameFromProperties("dataSource.service.isGenerate"));
        	if(isGenerate){
        		String path=utils.readPropertyByNameFromProperties("dataSource.api.path")+"\\src\\main\\java\\com\\ydcloud\\"+table.get("packageName")+"\\service\\"+table.get("jName")+"Service.java";
        		File file=new File(path);
        		if(file.exists()){
					try {
						CompilationUnit cu = JavaParser.parse(new FileInputStream(path));
						Optional<ClassOrInterfaceDeclaration> classByName = cu.getInterfaceByName(table.get("jName")+"Service");
						ClassOrInterfaceDeclaration orElse = classByName.orElse(null);
						//接口方法添加
						MethodDeclaration addMethod = orElse.addMethod(funName,Modifier.PUBLIC);
						addMethod.setType(retType); //添加返回类型
						//添加入参
						Set<Entry<String, String>> entrySet = params.entrySet();
						for (Entry<String, String> entry : entrySet) {
							addMethod.addParameter(entry.getValue(), entry.getKey());//添加入参
						}
				        addMethod.setBlockComment(funComment); //添加备注
				        addMethod.removeBody();
				        writeJava(cu, path);
					} catch (FileNotFoundException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

        		}
        	}
        	/*isGenerate=Boolean.parseBoolean(utils.readPropertyByNameFromProperties("dataSource.controller.isGenerate"));
        	if(isGenerate){
        		getNewFile("controller.ftl", table, utils.readPropertyByNameFromProperties("dataSource.web.path")+"\\src\\main\\java\\com\\yst\\hcloud\\gw\\controller\\"+table.get("packageName")+"\\"+table.get("jName")+"Controller.java");
        	}
        	isGenerate=Boolean.parseBoolean(utils.readPropertyByNameFromProperties("dataSource.entitys.isGenerate"));
        	if(isGenerate){
        		getNewFile("entitys.ftl", table, utils.readPropertyByNameFromProperties("dataSource.api.path")+"\\src\\main\\java\\com\\ydcloud\\"+table.get("packageName")+"\\domain\\"+table.get("jName")+".java");
        	}
            isGenerate=Boolean.parseBoolean(utils.readPropertyByNameFromProperties("dataSource.criteria.isGenerate"));
        	if(isGenerate){
        		getNewFile("criteria.ftl", table, utils.readPropertyByNameFromProperties("dataSource.api.path")+"\\src\\main\\java\\com\\ydcloud\\"+table.get("packageName")+"\\domain\\criteria\\"+table.get("jName")+"Criteria.java");
        	}
            isGenerate=Boolean.parseBoolean(utils.readPropertyByNameFromProperties("dataSource.saveVO.isGenerate"));
        	if(isGenerate){
        		getNewFile("saveVO.ftl", table, utils.readPropertyByNameFromProperties("dataSource.web.path")+"\\src\\main\\java\\com\\yst\\hcloud\\gw\\dto\\"+table.get("packageName")+"\\"+table.get("jName")+"SaveVO.java");
        	}
        	isGenerate=Boolean.parseBoolean(utils.readPropertyByNameFromProperties("dataSource.saveVO.isGenerate"));
        	if(isGenerate){
        		getNewFile("listVO.ftl", table, utils.readPropertyByNameFromProperties("dataSource.web.path")+"\\src\\main\\java\\com\\yst\\hcloud\\gw\\dto\\"+table.get("packageName")+"\\"+table.get("jName")+"ListVO.java");
        	}
        	isGenerate=Boolean.parseBoolean(utils.readPropertyByNameFromProperties("dataSource.detailVO.isGenerate"));
        	if(isGenerate){
        		getNewFile("detailVO.ftl", table, utils.readPropertyByNameFromProperties("dataSource.web.path")+"\\src\\main\\java\\com\\yst\\hcloud\\gw\\dto\\"+table.get("packageName")+"\\"+table.get("jName")+"DetailVO.java");
        	}*/
           
        }
    }
    
    public static Document getDocument(File file){

        //创建一个XML解析器
        SAXReader saxReader = new SAXReader();
        try {
            //读取Document对象
            Document document = null;
            document = saxReader.read(file);
            return document;
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return null;
    }
    //创建文件
    public static void createFileList(List<Map<String,Object>> tableList){
    	Boolean isGenerate=false;
        for(Map<String,Object> table:tableList){
        	isGenerate=Boolean.parseBoolean(utils.readPropertyByNameFromProperties("dataSource.bpmn.isGenerate"));
        	if(isGenerate){
        		//getNewFile("bpmn.ftl", table, utils.readPropertyByNameFromProperties("dataSource.service.workflow")+"\\src\\main\\resources\\diagrams\\"+table.get("sPname")+"_approval_process.bpmn");
        		//getNewFile("statusEnum.ftl", table, utils.readPropertyByNameFromProperties("dataSource.api.path")+"\\src\\main\\java\\com\\ydcloud\\"+table.get("packageName")+"\\enums\\"+table.get("jName")+"StatusEnum.java");
        		//getNewFile("taskKey.ftl", table, utils.readPropertyByNameFromProperties("dataSource.api.path")+"\\src\\main\\java\\com\\ydcloud\\"+table.get("packageName")+"\\enums\\"+table.get("jName")+"TaskKey.java");
        	}
        	isGenerate=Boolean.parseBoolean(utils.readPropertyByNameFromProperties("dataSource.dao.isGenerate"));
        	if(isGenerate){
        		getNewFile("dao.ftl", table, utils.readPropertyByNameFromProperties("dataSource.provider.path")+"\\src\\main\\java\\com\\ydcloud\\"+table.get("packageName")+"\\dao\\"+table.get("jName")+"Dao.java");
        	}
        	isGenerate=Boolean.parseBoolean(utils.readPropertyByNameFromProperties("dataSource.serviceImpl.isGenerate"));
        	if(isGenerate){
        		getNewFile("serviceImpl.ftl", table, utils.readPropertyByNameFromProperties("dataSource.provider.path")+"\\src\\main\\java\\com\\ydcloud\\"+table.get("packageName")+"\\service\\impl\\"+table.get("jName")+"ServiceImpl.java");
        	}
        	isGenerate=Boolean.parseBoolean(utils.readPropertyByNameFromProperties("dataSource.mapper.isGenerate"));
        	if(isGenerate){
        		getNewFile("mapper.ftl", table, utils.readPropertyByNameFromProperties("dataSource.provider.path")+"\\src\\main\\resources\\mybatis\\"+table.get("jName")+"Mapper.xml");
        	}
        	isGenerate=Boolean.parseBoolean(utils.readPropertyByNameFromProperties("dataSource.service.isGenerate"));
        	if(isGenerate){
        		getNewFile("service.ftl", table, utils.readPropertyByNameFromProperties("dataSource.api.path")+"\\src\\main\\java\\com\\ydcloud\\"+table.get("packageName")+"\\service\\"+table.get("jName")+"Service.java");
        	}
        	isGenerate=Boolean.parseBoolean(utils.readPropertyByNameFromProperties("dataSource.controller.isGenerate"));
        	if(isGenerate){
        		getNewFile("controller.ftl", table, utils.readPropertyByNameFromProperties("dataSource.web.path")+"\\src\\main\\java\\com\\yst\\hcloud\\gw\\controller\\"+table.get("packageName")+"\\"+table.get("jName")+"Controller.java");
        	}
        	isGenerate=Boolean.parseBoolean(utils.readPropertyByNameFromProperties("dataSource.entitys.isGenerate"));
        	if(isGenerate){
        		getNewFile("entitys.ftl", table, utils.readPropertyByNameFromProperties("dataSource.api.path")+"\\src\\main\\java\\com\\ydcloud\\"+table.get("packageName")+"\\domain\\"+table.get("jName")+".java");
        	}
            isGenerate=Boolean.parseBoolean(utils.readPropertyByNameFromProperties("dataSource.criteria.isGenerate"));
        	if(isGenerate){
        		getNewFile("criteria.ftl", table, utils.readPropertyByNameFromProperties("dataSource.api.path")+"\\src\\main\\java\\com\\ydcloud\\"+table.get("packageName")+"\\domain\\criteria\\"+table.get("jName")+"Criteria.java");
        	}
            isGenerate=Boolean.parseBoolean(utils.readPropertyByNameFromProperties("dataSource.saveVO.isGenerate"));
        	if(isGenerate){
        		getNewFile("saveVO.ftl", table, utils.readPropertyByNameFromProperties("dataSource.web.path")+"\\src\\main\\java\\com\\yst\\hcloud\\gw\\dto\\"+table.get("packageName")+"\\"+table.get("jName")+"SaveVO.java");
        	}
        	isGenerate=Boolean.parseBoolean(utils.readPropertyByNameFromProperties("dataSource.saveVO.isGenerate"));
        	if(isGenerate){
        		getNewFile("listVO.ftl", table, utils.readPropertyByNameFromProperties("dataSource.web.path")+"\\src\\main\\java\\com\\yst\\hcloud\\gw\\dto\\"+table.get("packageName")+"\\"+table.get("jName")+"ListVO.java");
        	}
        	isGenerate=Boolean.parseBoolean(utils.readPropertyByNameFromProperties("dataSource.detailVO.isGenerate"));
        	if(isGenerate){
        		getNewFile("detailVO.ftl", table, utils.readPropertyByNameFromProperties("dataSource.web.path")+"\\src\\main\\java\\com\\yst\\hcloud\\gw\\dto\\"+table.get("packageName")+"\\"+table.get("jName")+"DetailVO.java");
        	}
           
        }
       Map<String,Object> m=new HashMap<String,Object>();
        m.put("tableList", tableList);
        isGenerate=Boolean.parseBoolean(utils.readPropertyByNameFromProperties("dataSource.config.isGenerate"));
    	if(isGenerate){
    		getNewFile("provider-consumer-config.ftl", m, utils.readPropertyByNameFromProperties("dataSource.configuration.path")+"\\"+"provider-consumer-config.xml");
    	}
    }
    
    public static String getMysqlNameToJavaName(String name,boolean isUpper){
         name=name.trim();
         name=name.toLowerCase();
         do{
             int i = name.indexOf("_");
             String str="";
             if(i+2<name.length()){
                  str=name.substring(i+1, i+2);
                 
             }
             name=name.replace("_"+str, str.toUpperCase());
             
         }while(name.indexOf("_")>=0);
         if(isUpper){
             name=name.substring(0, 1).toUpperCase()+name.substring(1);
         }
        return name;
    }
    
    public static String getMysqlTypeToJavaType(String type){
        String jType="";
        type=type.trim();
        type=type.toUpperCase();
        if(type.indexOf("(")>=0){
            type=type.substring(0,type.indexOf("("));
        }
        switch (type) {
            case "VARCHAR":
               jType="java.lang.String"; 
                break;
            case "CHAR":
                jType="java.lang.String"; 
                 break;
            case "BLOB":
                jType="byte[]"; 
                 break;
            case "TEXT":
                jType="java.lang.String"; 
                 break;
            case "INTEGER":
                jType="java.lang.Long"; 
                 break;
            case "TINYINT":
                jType="java.lang.Integer"; 
                 break;
            case "SMALLINT":
                jType="java.lang.Integer"; 
                 break;
            case "MEDIUMINT":
                jType="java.lang.Integer"; 
                 break;
            case "BIT":
                jType="java.lang.Boolean"; 
                 break;
            case "BIGINT":
                jType="java.lang.Long"; 
                 break;
            case "FLOAT":
                jType="java.lang.Float"; 
                 break;
            case "DOUBLE":
                jType="java.lang.Double"; 
                 break;
            case "DECIMAL":
                jType="java.math.BigDecimal"; 
                 break;
            case "BOOLEAN":
                jType="java.lang.Integer"; 
                 break;
            case "ID":
                jType="java.lang.Long"; 
                 break;
            case "DATE":
                jType="java.util.Date"; 
                 break;
            case "TIME":
                jType="java.util.Date"; 
                 break;
            case "DATETIME":
                jType="java.util.Date"; 
                 break;
            case "TIMESTAMP":
                jType="java.util.Date"; 
                 break;
            case "YEAR":
                jType="java.util.Date"; 
                 break;
            case "INT":
                jType="java.lang.Integer"; 
                 break;
            default:
                jType="java.lang.String"; 
                break;
        }
        return jType;
    }
    
    public static String getMysqlTypeToMybatisType(String type){
        String sType="";
        type=type.trim();
        type=type.toUpperCase();
        if(type.indexOf("(")>=0){
            type=type.substring(0,type.indexOf("("));
        }
        switch (type) {
            case "VARCHAR":
            	sType="VARCHAR"; 
                break;
            case "CHAR":
            	sType="CHAR"; 
                 break;
            case "BLOB":
            	sType="BLOB"; 
                 break;
            case "TEXT":
            	sType="VARCHAR"; 
                 break;
            case "INTEGER":
            	sType="INTEGER"; 
                 break;
            case "TINYINT":
            	sType="TINYINT"; 
                 break;
            case "SMALLINT":
            	sType="SMALLINT"; 
                 break;
            case "MEDIUMINT":
            	sType="INTEGER"; 
                 break;
            case "BIT":
            	sType="BOOLEAN"; 
                 break;
            case "BIGINT":
            	sType="BIGINT"; 
                 break;
            case "FLOAT":
            	sType="FLOAT"; 
                 break;
            case "DOUBLE":
            	sType="DOUBLE"; 
                 break;
            case "DECIMAL":
            	sType="DECIMAL"; 
                 break;
            case "BOOLEAN":
            	sType="BOOLEAN"; 
                 break;
            case "ID":
            	sType="BIGINT"; 
                 break;
            case "INT":
            	sType="INTEGER"; 
                 break;
            case "DATE":
            	sType="TIMESTAMP"; 
                 break;
            case "TIME":
            	sType="TIMESTAMP"; 
                 break;
            case "DATETIME":
            	sType="TIMESTAMP"; 
                 break;
            case "TIMESTAMP":
            	sType="TIMESTAMP"; 
                 break;
            case "YEAR":
            	sType="TIMESTAMP"; 
                 break;
            default:
            	sType=type; 
                break;
        }
        return sType;
    }
    
    
    
    /**
     * 
     * Description: <br>
     * 1、…<br>
     * 2、…<br>
     * Implement: <br>
     * 1、…<br>
     * 2、…<br>
     * 
     * @param templateName 模板名称
     * @param paramMap 参数map
     * @param fileName  生成文件目录及名称
     * @see
     */
    public static void getNewFile(String templateName,Map<String, Object> paramMap,String fileName){
        String filePath = System.getProperty("user.dir");
        String filePathSub=filePath+"\\template";
        filePath=fileName.substring(0,fileName.lastIndexOf("\\"));
        try {
            File file =new File(filePath);    
	        //如果文件夹不存在则创建    
	        if  (!file .exists()  && !file .isDirectory()){ 
	            file.mkdirs();   
	        } 
            Configuration configuration = new Configuration();  
            configuration.setDirectoryForTemplateLoading(new File(filePathSub));
            configuration.setObjectWrapper(new DefaultObjectWrapper());  
           // configuration.setDefaultEncoding("UTF-8");   //这个一定要设置，不然在生成的页面中 会乱码  
            //获取或创建一个模版。  
            Template template = configuration.getTemplate(templateName); 
            Writer writer  = new OutputStreamWriter(new FileOutputStream(fileName),"UTF-8");  
            template.process(paramMap, writer);  
        }catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (TemplateException e) {  
            e.printStackTrace();  
        }    
    }
    
    /**
     * 把修改后的Document对象写出到xml文档中
     * @param document
     * @throws IOException
     */
    public static void writeJava(CompilationUnit cu,String path) throws IOException {
    	 try  
         {      
           // 创建文件对象  
           File fileText = new File(path);  
           // 向文件写入对象写入信息  
           FileWriter fileWriter = new FileWriter(fileText);  
           // 写文件        
           fileWriter.write(cu.toString());  
           // 关闭  
           fileWriter.close();  
         }  
         catch (IOException e)  
         {  
           //  
           e.printStackTrace();  
         }   
    }
    
    /**
     * 把修改后的Document对象写出到xml文档中
     * @param document
     * @throws IOException
     */
    public static void writeXml(Document document,String path) throws IOException {
        //把修改后的Document对象写出到xml文档中
        FileOutputStream out = new FileOutputStream(path);
        //比较美观的排版方式 用于人阅读
        OutputFormat format = OutputFormat.createPrettyPrint();

        //紧凑型的排版方式 ，主要用于程序运行中使用 减少不必要的空格换行等
        //OutputFormat format2 = OutputFormat.createCompactFormat();

        format.setEncoding("utf-8");
        XMLWriter writer = new XMLWriter(out,format);
        writer.write(document);
        writer.close();
    }
}  